// pages/home-music/index.js
import {
  rankingStore,
  rankingMap,
  playerStore
} from "../../store/index"
import {
  getBanners,
  getSongMenu
} from "../../service/api_music"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    recommendSongs: [],

    hotSongMenu: [],
    recommendSonMenu: [],

    rankings: {
      0: {},
      2: {},
      3: {}
    },

    currentSong: {},
    isPlaying: false,
    playAnimState: "paused"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 页面测试
    // playerStore.dispatch("playMusicWithSongIdAction", {
    //   id: 1808492017
    // })
    // 获取当前页面数据
    this.getPageData()

    // 发起共享数据的请求
    rankingStore.dispatch("getRankingDataAction")

    // 数据监听的 封装(歌单 & 首页播放器)
    this.setupPlayStoreListener()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 因为是首页，不存在卸载，如果其他页面可以卸载监听
    // rankingStore.offState("newRanking", this.getNewRankingHandler)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // ========================   网络请求   ========================
  getPageData: function () {
    // 获取轮播图
    getBanners().then(res => {
      this.setData({
        banners: res.banners
      })
    })
    // 获取热门歌单
    getSongMenu().then(res => {
      this.setData({
        hotSongMenu: res.playlists
      })
    })
    // 获取推荐歌单
    getSongMenu("华语").then(res => {
      this.setData({
        recommendSonMenu: res.playlists
      })
    })
  },

  // 巅峰榜数据 - 共享获取（3个榜单）
  getRankingHandler: function (idx) {
    return (res) => {
      if (Object.keys(res).length === 0) return
      // console.log("idx:", idx);
      // 处理数据
      const name = res.name
      const coverImgUrl = res.coverImgUrl
      const playCount = res.playCount
      const songList = res.tracks.slice(0, 3)
      // 数据整理
      const rankingObj = {
        name,
        coverImgUrl,
        playCount,
        songList
      }
      // 采用展开运算符，进行浅拷贝，同时进行动态属性赋值
      const originRankings = {
        ...this.data.rankings,
        [idx]: rankingObj
      }
      // 进行数据拼接（如果是数组，请求前后确定不了，已修改为对象）
      // originRankings.push(rankingObj)
      this.setData({
        rankings: originRankings
      })
      // console.log(this.data.rankings);
    }
  },

  // 巅峰榜数据 - 共享获取（已弃用，已抽取为高阶函数，复用性强）
  getNewRankingHandler: function (res) {
    if (Object.keys(res).length === 0) return
    // 处理数据
    const name = res.name
    const coverImgUrl = res.coverImgUrl
    const songList = res.tracks.slice(0, 3)
    // 数据整理
    const rankingObj = {
      name,
      coverImgUrl,
      songList
    }
    // 采用展开运算符，进行浅拷贝
    const originRankings = [...this.data.rankings]
    // 进行数据拼接
    originRankings.push(rankingObj)
    this.setData({
      rankings: originRankings
    })
  },

  // ========================   事件处理   ========================
  // 搜索后，跳转搜索列表页
  hanleSearchClick: function () {
    wx.navigateTo({
      url: '/packageDetail/pages/detail-search/index'
    })
  },
  // 1.1-歌曲-详情页跳转
  handleMoreClick: function () {
    this.navigateToDetailSongsPage("hotRanking")
  },
  // 1.2-多个歌曲-详情页跳转封装
  navigateToDetailSongsPage: function (rankingName) {
    wx.navigateTo({
      url: `/packageDetail/pages/detail-songs/index?ranking=${rankingName}&type=rank`,
    });
  },
  // 巅峰榜-详情页跳转
  handleRankingItemClick: function (event) {
    const idx = event.currentTarget.dataset.idx
    const rankingName = rankingMap[idx]
    this.navigateToDetailSongsPage(rankingName)
  },

  // 首页播放器暂停&播放
  handlePlayBtnClick: function () {
    playerStore.dispatch("changeMusicPlayStatusAction", !this.data.isPlaying)
  },
  // 播放器点击跳转
  handlePlayBarClick: function () {
    wx.navigateTo({
      url: '/packagePlayer/pages/music-player/index?id=' + this.data.currentSong.id,
    })
  },

  // ========================   数据处理   ========================
  // 歌曲列表&索引的store存储
  handleSongItemClick: function (event) {
    const index = event.currentTarget.dataset.index
    console.log("setIndex-1:", index);
    playerStore.setState("playListSongs", this.data.recommendSongs)
    playerStore.setState("playListIndex", index)
  },
  // 首页播放器数据获取
  setupPlayStoreListener: function () {
    // 1.排行榜监听
    // 1.1 从store获取共享的数据 - 热门【推荐歌曲】
    rankingStore.onState("hotRanking", res => {
      if (!res.tracks) return
      const recommendSongs = res.tracks.slice(0, 6)
      this.setData({
        recommendSongs
      })
      // console.log(recommendSongs);
    })

    // 从store获取共享的数据 - 0：新歌  2：原创  3：飙升
    rankingStore.onState("newRanking", this.getRankingHandler(0))
    rankingStore.onState("originRanking", this.getRankingHandler(2))
    rankingStore.onState("upRanking", this.getRankingHandler(3))

    // 1.2 采用新方法监听巅峰榜
    // playerStore.onStates(["newRanking", "originRanking", "upRanking"], ({
    //   newRanking,
    //   originRanking,
    //   upRanking
    // }) => {
    //   if (newRanking){
    //     this.getRankingHandler(0)
    //   }
    //   if (originRanking) {
    //     this.getRankingHandler(2)
    //   }
    //   if (upRanking) {
    //     this.getRankingHandler(3)
    //   }
    // })

    // 2.播放器监听
    playerStore.onStates(["currentSong", "isPlaying"], ({
      currentSong,
      isPlaying
    }) => {
      if (currentSong) this.setData({
        currentSong
      })
      if (isPlaying !== undefined) this.setData({
        isPlaying,
        playAnimState: isPlaying ? "running" : "paused"
      })
    })
  }

})